package main

import (
	"context"
	"encoding/csv"
	"fmt"
	"log"
	"os"

	"github.com/zeromicro/go-zero/core/logc"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go.mongodb.org/mongo-driver/mongo/readpref"
)

type Person struct {
	Name  string `bson:"name"`
	Age   int    `bson:"age"`
	Email string `bson:"email"`
}

type MongoClient struct {
	uri         string
	mongoDBName string //使用的数据库
	client      *mongo.Client
	collection  *mongo.Collection
}

var mongoclient *MongoClient

type Requestion struct {
	Title   string `json:"title"`
	Content []struct {
		// Type string `json:"type"`
		Text string `json:"text"`
	} `json:"content"`
}

func main() {
	// 设置MongoDB连接URI
	mongoclient = &MongoClient{}
	mongoclient.uri = "mongodb://root:adgjmptw3221658.@dc04.iotdreamcatcher.net:8017"
	mongoclient.mongoDBName = "faq"

	// 创建客户端选项
	clientOptions := options.Client().ApplyURI(mongoclient.uri)

	// 连接到MongoDB
	ctx := context.TODO()
	client, err := mongo.Connect(ctx, clientOptions)
	if err != nil {
		log.Fatal(err)
	}

	// 检查连接
	err = client.Ping(ctx, readpref.Primary())
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Connected to MongoDB!")

	// 获取数据库和集合
	collection := client.Database(mongoclient.mongoDBName).Collection("question")

	mongoclient.client = client
	mongoclient.collection = collection

	// 插入文档
	// person := Person{Name: "Alice", Age: 30, Email: "alice@example.com"}
	// insertResult, err := collection.InsertOne(ctx, person)
	// if err != nil {
	//     log.Fatal(err)
	// }
	// fmt.Println("Inserted document with ID:", insertResult.InsertedID)

	// 查询文档
	filter := make(map[string]interface{})
	filter["language"] = "EN"

	var result []Requestion
	err = mongoclient.QueryMultiData(ctx, filter, nil, &result, 0)
	if err != nil {
		log.Fatal(err)
	}
	// fmt.Printf("Found document: %+v\n", result)

	err = ResultWriteCVS(ctx, result)
	if err != nil {
		log.Fatal(err)
	}

	// 关闭连接
	err = client.Disconnect(ctx)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Connection to MongoDB closed.")
}

func (c *MongoClient) QueryMultiData(ctx context.Context, keys map[string]interface{}, sortKeysMap map[string]interface{}, dest interface{}, limit int64) error {
	logc.Infof(ctx, "keys:%+v,sortKeysMap:%+v,limit:%d", keys, sortKeysMap, limit)
	var sortParam *options.FindOptions = nil
	if len(sortKeysMap) != 0 {
		sortParam = options.Find().SetSort(bson.M(sortKeysMap))
	}
	cursor, err := c.collection.Find(ctx, bson.M(keys),
		options.Find().SetLimit(limit), sortParam,
	)
	if err != nil {
		logc.Errorf(ctx, "err:%+v", err)
		if err == mongo.ErrNoDocuments {
			return nil
		}
		return err
	}
	if err = cursor.Err(); err != nil {
		logc.Errorf(ctx, "err:%+v", err)
		return err
	}
	defer cursor.Close(ctx)
	cursor.All(ctx, dest)
	return err
}

func ResultWriteCVS(ctx context.Context, resluts []Requestion) error {
	// 创建 CSV 文件
	file, err := os.Create("result.csv")
	if err != nil {
		fmt.Println("Error creating CSV file:", err)
		return err
	}
	defer file.Close()

	// 创建 CSV Writer
	writer := csv.NewWriter(file)
	defer writer.Flush()

	// 写入 CSV 标题行
	header := []string{"Title", "Content"}
	if err := writer.Write(header); err != nil {
		fmt.Println("Error writing header to CSV:", err)
		return err
	}

	// 写入 JSON 数据到 CSV
	for _, safetyInfo := range resluts {
		for _, content := range safetyInfo.Content {
			if content.Text == "xxx" || content.Text == "按时" {
				continue
			}
			row := []string{safetyInfo.Title, content.Text}
			if err := writer.Write(row); err != nil {
				fmt.Println("Error writing row to CSV:", err)
				return err
			}
		}
	}

	fmt.Println("CSV file created successfully: result.csv")
	return nil
}
